""" 下载ts文件 """
import requests
import datetime
import os
import json

# 读取json文件内容,返回字典格式
def getJson():
    # 获取相对位置
    path = os.path.dirname(os.path.abspath(__file__))
    with open(path+'\config.json', 'r', encoding='utf8')as fp:
        myjson = json.load(fp)
    return myjson


# https://blog.csdn.net/LANGZI7758521/article/details/119999256
# 删除文件夹下面的所有文件
# path 要删除所有文件的目录
def del_file(path):
    if not os.path.exists(path):
        return

    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            del_file(c_path)
        else:
            os.remove(c_path)


# 分析本地m3u8文件，获取所有的ts文件的url
# m3u8_path 本地m3u8文件所在位置
# base_url 请求ts文件的url根地址
def get_ts_urls(m3u8_path, base_url):
    path = os.path.dirname(os.path.abspath(__file__))
    urls = []
    with open(path+'\index.m3u8', "r") as file:
        lines = file.readlines()
        for line in lines:
            if not line.startswith("#"):
                urls.append(base_url+line.strip("\n"))
    return urls


# 下载ts文件
# ts_urls 是ts文件的url集合
# download_path 是下载ts文件后的保存地址
def download(ts_urls, download_path):
    if not os.path.exists(download_path):
        os.mkdir(download_path)  

    for i in range(len(ts_urls)):
        ts_url = ts_urls[i]
        file_name = ts_url.split("/")[-1]
        print("开始下载 %s" % file_name)
        start = datetime.datetime.now().replace(microsecond=0)
        try:
            response = requests.get(ts_url, stream=True, verify=False)
        except Exception as e:
            print("异常请求：%s" % e.args)
            return
        
        name = '0000'
        if i < 10:
            name = "000" + str(i)
        elif i < 100:
            name = "00" + str(i)
        elif i < 1000:
            name = "0" + str(i)

        ts_path = download_path+"/{0}.ts".format(name)
        with open(ts_path, "wb+") as file:
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:
                    file.write(chunk)

        end = datetime.datetime.now().replace(microsecond=0)
        print("耗时：%s" % (end-start))
    print("=====================")


if __name__ == '__main__':
    print(getJson()["download_path"])
    # 请求ts文件的url根地址
    base_url = getJson()["base_url"]
    # m3u8是本地的文件路径
    # m3u8_path = "C:/weijun.wu/front_end_learning_code/_项目/视频/音频下载/m3u8格式视频/index.m3u8"
    # 下载的ts文件的保存地址
    # download_path = "C:/weijun.wu/front_end_learning_code/_项目/视频/音频下载/m3u8格式视频/download"

    del_file(getJson()["download_path"])
    # print(get_ts_urls(getJson()["m3u8_path"], base_url))
    m3u8_path = get_ts_urls("",base_url)
    download(m3u8_path, getJson()["download_path"])

    print("**************************")
